//
//  WmcUploadQueueV2DBManager.swift
//  YPWatermarkCamera
//
//  Created by 周诗松 on 2022/6/14.
//

import Foundation
import YPBedrock

// MARK: - 扩展WmcUploadQueueV2DBManager + WmcDBProtocol

extension WmcUploadQueueV2DBManager: WmcDBProtocol {
    static var tableName: String {
        guard let userId = WmcLoginManager.shared.yupaoAccountModel?.userId, !userId.isEmpty else {
            return ""
        }
        let name = "upload_queue_v2_\(userId)"
        return name
    }

    static var dataType: [WmcDBManager.DataType] {
        return [
            .primaryKey(),
            .varchar(name: "uuid"),
            .varchar(name: "photo_path"),
            .varchar(name: "preview_image_path"),
            .varchar(name: "parameters"),
            .varchar(name: "syncInfo"),
        ]
    }
}

// MARK: - [WmcUploadQueueV2DBManager]

struct WmcUploadQueueV2DBManager {
    /// 保存待上传的图片
    /// - Parameters:
    ///   - model: 图片model
    ///   - resultBlock: 结果
    static func insert(model: WmcUploadImageV2Model,
                       resultBlock: YPBlock.OneParam<Bool>? = nil)
    {
        let tableName = WmcUploadQueueV2DBManager.tableName
        if tableName.isEmpty {
            resultBlock?(false)
            return
        }
        
        var parametersJsonString: String = ""
        var syncInfoJsonString: String = ""
        
        if let data = try? JSONSerialization.data(withJSONObject: model.parameters, options: []) {
            parametersJsonString = String(data: data, encoding: String.Encoding.utf8) ?? ""
        }
        
        if let syncInfo = model.syncInfo, let data = try? JSONSerialization.data(withJSONObject: syncInfo, options: []) {
            syncInfoJsonString = String(data: data, encoding: String.Encoding.utf8) ?? ""
        }
        
        if parametersJsonString.isEmpty || syncInfoJsonString.isEmpty {
            resultBlock?(false)
            return
        }

        let dataList: [WmcDBManager.InsertData] = [
            .init(column: Self.dataType[1], value: model.uuid),
            .init(column: Self.dataType[2], value: model.photoPath),
            .init(column: Self.dataType[3], value: model.previewImagePath),
            .init(column: Self.dataType[4], value: parametersJsonString),
            .init(column: Self.dataType[5], value: syncInfoJsonString),
        ]

        WmcDBManager.shared.insertData(tableName: tableName, insertData: dataList, resultBlock: resultBlock)
    }

    /// 查询待上传的图片
    /// - Parameter resultBlock: 结果
    static func query(resultBlock: YPBlock.OneParam<[WmcUploadImageV2Model]>? = nil) {
        let tableName = WmcUploadQueueV2DBManager.tableName
        if tableName.isEmpty {
            resultBlock?([])
            return
        }

        WmcDBManager.shared.searchCustomData(tableName: tableName) { list in
            var result: [WmcUploadImageV2Model] = []
            list.forEach { data in
                var dataDic = data
                if let jsonString = data["parameters"] as? String, let jsonData: Data = jsonString.data(using: .utf8), let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) {
                    dataDic["parameters"] = dict
                }
                
                if let jsonString = data["syncInfo"] as? String, let jsonData: Data = jsonString.data(using: .utf8), let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) {
                    dataDic["syncInfo"] = dict
                }
                
                if let photoPath = data["photo_path"] as? String {
                    dataDic["photoPath"] = photoPath
                }
                
                if let previewImagePath = data["preview_image_path"] as? String {
                    dataDic["previewImagePath"] = previewImagePath
                }
                
                if let model = WmcUploadImageV2Model.deserialize(from: dataDic) {
                    result.append(model)
                }
            }
            resultBlock?(result)
        }
    }

    /// 删除待上传的图片
    /// - Parameters:
    ///   - model: 图片model
    ///   - resultBlock: 结果
    static func delete(model: WmcUploadImageV2Model,
                       resultBlock: YPBlock.OneParam<Bool>? = nil)
    {
        let tableName = WmcUploadQueueV2DBManager.tableName
        if tableName.isEmpty {
            resultBlock?(false)
            return
        }

        let condition = "where uuid = '\(model.uuid)'"

        WmcDBManager.shared.deleteCustomData(tableName: tableName, condition: condition, resultBlock: resultBlock)
    }
}
